﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

namespace AssemblyExplorer
{
    public static class ReflectionHelper
    {
        public static string[] GetTypesByInterface(string assemblyFile, Type pluginInterface)
        {
            Assembly assembly = Assembly.LoadFrom(assemblyFile);
            return GetTypesByInterface(assembly, pluginInterface);
        }

        public static string[] GetTypesByInterface(Assembly assembly, Type pluginInterface)
        {
            List<string> plugins = new List<string>();
            foreach (Type type in assembly.GetTypes())
            {
                if (pluginInterface.IsAssignableFrom(type))
                {
                    plugins.Add(type.FullName);
                }
            }
            return plugins.ToArray();
        }

        public static CompilerResults Compile(string code)
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            string cb = Assembly.GetExecutingAssembly().CodeBase.Substring(8);
            cp.ReferencedAssemblies.Add(cb);
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;
            var res = provider.CompileAssemblyFromSource(cp, code);
            return res;
        }
    }
}
